/*

  The MIT License

  Copyright (c) 2008 - 2011. Dimarik

  Permission is hereby granted, free of charge, to any person obtaining a copy
  of this software and associated documentation files (the "Software"), to deal
  in the Software without restriction, including without limitation the rights
  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  copies of the Software, and to permit persons to whom the Software is
  furnished to do so, subject to the following conditions:

  The above copyright notice and this permission notice shall be included in
  all copies or substantial portions of the Software.

  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  THE SOFTWARE.

*/

package ru.goodcore.text
{

import flash.events.Event;
import flash.text.StyleSheet;

[Event(name="change", type="flash.events.Event")]

/**
 *  @author				Dimarik
 *  @version			1.1
 *  @langversion		3.0
 *  @playerversion		9.0
 * 
 */
public class StyleSheet extends flash.text.StyleSheet {

	//-------------------------------------------------------------------------
	//
	//   Class constants
	//
	//-------------------------------------------------------------------------

	//-------------------------------------------------------------------------
	//
	//   Constructor
	//
	//-------------------------------------------------------------------------

	/**
	 * Constructor 
	 */
	public function StyleSheet() {
		super();
	}

	//-------------------------------------------------------------------------
	//
	//   Variables & const
	//
	//-------------------------------------------------------------------------

	//-------------------------------------------------------------------------
	//
	//   Overridden properties:	flash.text.StyleSheet
	//
	//-------------------------------------------------------------------------

	//-------------------------------------------------------------------------
	//
	//   Properties
	//
	//-------------------------------------------------------------------------

	private const _changedStyles:	Array = new Array();

	public function get changedStyles():Array {
		return this._changedStyles.slice();
	}

	//-------------------------------------------------------------------------
	//
	//   Private variables
	//
	//-------------------------------------------------------------------------

	/**
	 * @private
	 */
	private var _cssTable:	Object = new Object();

	//-------------------------------------------------------------------------
	//
	//   Overridden methods: flash.text.StyleSheet
	//
	//-------------------------------------------------------------------------

	/**
	 * @inheritDoc
	 */
	public override function parseCSS(CSSText:String):void {
		super.parseCSS(CSSText);
		this.syncSelectors.apply(this, super.styleNames);
	}

	/**
	 * @inheritDoc
	 */
	public override function setStyle(styleName:String, styleObject:Object):void {
		super.setStyle(styleName, styleObject);
		this.syncSelectors.call(this, styleName);
	}

	/**
	 * @inheritDoc
	 */
	public override function clear():void {
		const selectorNames:	Array = super.styleNames;
		var selectorLegacy:		Object;
		var selectorPrimary:	StyleTable;

		for each (var selectorName:String in selectorNames) {
			selectorLegacy = super.getStyle(selectorName);
			selectorPrimary = this._cssTable[selectorName] as StyleTable;

			if ( !selectorPrimary )
				continue;

			for (var styleName:String in selectorLegacy)
				selectorPrimary[styleName] = undefined;

			selectorPrimary.clear();
		}

		super.clear();
	}

	//-------------------------------------------------------------------------
	//
	//   Protected methods
	//
	//-------------------------------------------------------------------------

	//-------------------------------------------------------------------------
	//
	//   Public methods
	//
	//-------------------------------------------------------------------------

	public function mergeStyleSheet(styleSheet:flash.text.StyleSheet):void {
		var nSelectorNames:		Array = styleSheet.styleNames;//.slice();
		var nName:				String;

		var oSelector:			Object;
		var nSelector:			Object;
		var doRemove:			Boolean;

		// Выясним какие стили в каких селекторах изменились
		// И сформируем список изменившихся селекторов
		var run:	Boolean = true;
		var i:		uint = 0;

		while (run) {
			nName = nSelectorNames[i];

			// Необходимо пробежаться по стилям нового и старого селектора
			// и сравнить их значения
			oSelector = super.getStyle(nName);
			nSelector = styleSheet.getStyle(nName);

			doRemove = true;

			for (var nKey:String in nSelector) {

				if (
					   !(nKey in oSelector) // В старом селекторе нет такого стиля, как в новом.
					|| oSelector[nKey] !== nSelector[nKey] // Значения стилей не совпадают.

				) {
					doRemove = false;
					break;
				}

			}

			if ( doRemove )
				nSelectorNames.splice(i, 1);
			else {
				i++;
				this.setStyle( nName, styleSheet.getStyle(nName) );
			}

			run = i < nSelectorNames.length;
		}

		if ( nSelectorNames.length ) {;
			this._changedStyles.push.apply(this, nSelectorNames);
			super.dispatchEvent( new Event(Event.CHANGE) );
			this._changedStyles.splice(0, this._changedStyles.length);
		}

	}

	//-------------------------------------------------------------------------
	//
	//   Private methods
	//
	//-------------------------------------------------------------------------

	/**
	 * @private
	 */
	private function syncSelectors(...selectorNames:Array):void {
		var selectorLegacy:		Object;
		var selectorPrimary:	StyleTable;

		for each (var selectorName:String in selectorNames) {
			selectorLegacy = super.getStyle(selectorName);
			selectorPrimary = this._cssTable[selectorName] as StyleTable;

			if ( !selectorPrimary ) {
				selectorPrimary = new StyleTable();
				this._cssTable[selectorName] = selectorPrimary;
			}

			for (var styleName:String in selectorLegacy) {
				selectorPrimary[styleName] = selectorLegacy[styleName];
			}

		}
	}

	//-------------------------------------------------------------------------
	//
	//   Event handlers
	//
	//-------------------------------------------------------------------------


}
}